package com.demo.modules.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.demo.common.base.R;
import com.demo.common.base.controller.BaseController;
import com.demo.common.enums.REnum;
import com.demo.common.enums.TokenTypeEnum;
import com.demo.common.utils.IPUtils;
import com.demo.modules.sys.entity.SysUserEntity;
import com.demo.modules.sys.entity.SysUserTokenEntity;
import com.demo.modules.sys.form.SysLoginForm;
import com.demo.modules.sys.service.*;
import lombok.AllArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 登录相关
 *
 * @author Mark sunlightcs@gmail.com
 */
@AllArgsConstructor
@RestController
@RequestMapping("/login")
public class SysLoginController extends BaseController {

    private final ShiroService shiroService;
    private final SysCaptchaService sysCaptchaService;
    private final SysLogService sysLogService;
    private final SysUserService sysUserService;
    private final SysUserTokenService sysUserTokenService;

    /**
     * 验证码
     */
    @GetMapping("captcha.jpg")
    public R captcha(String uuid) throws IOException {

        // 获取图片验证码
        BufferedImage image = sysCaptchaService.getCaptcha(uuid);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
        byte[] imageData = out.toByteArray();
        return R.ok(imageData);
    }

    /**
     * WEB后台登录
     */
    @PostMapping("/sys")
    public R sysLogin(SysLoginForm form, HttpServletRequest request) {
        SysUserEntity user = shiroService.login(form, TokenTypeEnum.SYS.getValue(), IPUtils.getIpAddr(request));
        SysUserTokenEntity sysUserTokenEntity = sysUserTokenService.createToken(user.getId(), TokenTypeEnum.SYS.getValue());
        return R.ok().put("user", user).put("token", sysUserTokenEntity.getToken());
    }

    /**
     * 获取登录的用户信息
     */
    @GetMapping("/user/info")
    public R<SysUserEntity> info() {
        return R.ok(getUser());
    }

    /**
     * 退出
     */
    @PostMapping("/sys/logout")
    public R sysLogout(HttpServletRequest request) {
        // 记录日志
        sysLogService.saveLog(getUserId(), "用户登出", IPUtils.getIpAddr(request));
        SecurityUtils.getSubject().logout();
        sysUserTokenService.logout(getUserId(), TokenTypeEnum.SYS.getValue());
        return R.ok();
    }

    /**
     * APP登录
     */
    @PostMapping("/app")
    public R appLogin(@RequestBody SysLoginForm form, HttpServletRequest request) {
        SysUserEntity user = shiroService.login(form, TokenTypeEnum.APP.getValue(), IPUtils.getIpAddr(request));
        SysUserTokenEntity sysUserTokenEntity = sysUserTokenService.createToken(user.getId(), TokenTypeEnum.APP.getValue());
        return R.ok().put("token", sysUserTokenEntity.getToken());
    }

    /**
     * 第三方登录
     */
    @PostMapping("/other")
    public R otherLogin(@RequestBody SysLoginForm form, HttpServletRequest request) {
        SysUserEntity user = shiroService.login(form, form.getTokenType(), IPUtils.getIpAddr(request));
        return R.ok();
    }

    /**
     * 第三方账号绑定
     */
    @PostMapping("/other/bind")
    public R otherBind(@RequestBody SysUserEntity params) {
        // 账号是否存在
        SysUserEntity user = sysUserService.getOne(new LambdaQueryWrapper<SysUserEntity>()
                        .eq(SysUserEntity::getRealName, params.getRealName())
                        .eq(SysUserEntity::getIdcard, params.getIdcard())
                        .eq(SysUserEntity::getMobile, params.getMobile())
                , false);
        if (user == null || user.getId() == null) {
            return R.error(REnum.UN_LOGIN.getCode(), "账号不存在");
        }
        // 绑定
        user.setOpenid(params.getOpenid());
        sysUserService.updateById(user);

        return R.ok();
    }


    /**
     * 第三方账号解绑
     */
    @PostMapping("/other/unbind/{userId}")
    public R otherUnbind(@PathVariable("userId") Long userId) {
        // 账号是否存在
        SysUserEntity user = sysUserService.getById(userId);
        if (user == null || user.getId() == null) {
            return R.error(REnum.UN_LOGIN.getCode(), "账号不存在");
        }
        // 解绑
        user.setOpenid("");
        sysUserService.updateById(user);

        return R.ok();
    }


    /**
     * APP退出登录
     */
    @PostMapping("/app/logout")
    public R appLogout() {
        shiroService.logout(getUserId());
        sysUserTokenService.logout(getUserId(), TokenTypeEnum.APP.getValue());
        return R.ok();
    }

}
